package com.app.miwawa.ext.util.sms;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.framework.common.ext.util.JsonUtil;

public class SendMsg {
	
	private String url;
	
	private List<BasicNameValuePair> params;

	/**
	 * 发送短信.
	 * PS:批量发送时，手机号用“,”分隔
	 * @param mobile
	 * @param content
	 * @return
	 * @throws UnsupportedEncodingException
	 * @author chanlong(陈龙)
	 * @date 2016年5月18日 下午3:50:28
	 */
	public String sendBatch(String mobiles, String content) throws UnsupportedEncodingException {
		return this.addParams("mobiles", mobiles).addParams("content", content).conurl().getCodetype();
	}

	/**
	 * 获取短信余额.
	 * @return
	 * @author chanlong(陈龙)
	 * @date 2016年5月18日 下午3:47:08
	 */
	public String getbalance() {
		return conurl().getCodetype();
	}

	/*
	 * 请求URL
	 */
	private Result conurl() {
		Result result = new Result();
		InputStream input = null;
		try {
			// 创建POST请求链接
			HttpClientBuilder builder = HttpClientBuilder.create();
			CloseableHttpClient client = builder.build();
			HttpPost post = new HttpPost(url);
			
			// 设置POST参数
			if(params != null && !params.isEmpty()){
				UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(params, "UTF-8");
				post.setEntity(encodedFormEntity);
			}
	            
			// 执行POST请求
			HttpResponse response = client.execute(post);
			
			// 返回响应内容
			input = response.getEntity().getContent();
			result = JsonUtil.getBean(IOUtils.toString(input, Consts.UTF_8), Result.class);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (input != null) IOUtils.closeQuietly(input);
		}
		
		return result;
	}
	
	public SendMsg() {

	}
	
	public SendMsg(String url, String account, String password){
		this.url = url;
		this.addParams("account", account)
			.addParams("password", password);
	}
	
	public SendMsg addParams(final String key, final String val){
		if(params == null){
			params = new ArrayList<BasicNameValuePair>();
		}
		params.add(new BasicNameValuePair(key, val));
		return this;
	}
}
